package com.hongdee.crm.task.dao.impl;

import com.hongdee.base.basedao.impl.BaseDaoImpl;
import com.hongdee.crm.Constant;
import com.hongdee.crm.car.entity.TCrmCar;
import com.hongdee.crm.maintain.entity.TCrmCarMaintain;
import com.hongdee.crm.task.dao.ITCrmCarMaintainTaskDao;
import com.hongdee.crm.task.dao.ITCrmTaskDao;
import com.hongdee.crm.task.dto.WorkOrderDTO;
import com.hongdee.crm.task.entity.TCrmTask;
import com.hongdee.crm.task.service.ITCrmCarMaintainTaskService;
import com.hongdee.crm.workorder.entity.TCrmCarWorkOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.*;

/**
 * 名  称: TCrmMaintainTaskDaoImpl
 * 类  型: class
 * 描  述: 保养类任务相关
 * 路  径: com.hongdee.crm.task.dao.impl
 * 作  者: wangshuai
 * 日  期:2017/2/28 10:23
 */
@Service
public class TCrmMaintainTaskDaoImpl extends BaseDaoImpl implements ITCrmCarMaintainTaskDao {

    @Autowired
    @Qualifier("jdbcTemplate")
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private ITCrmTaskDao crmTaskDao;

    /**
     * 方法名称:getTimeStr
     * 方法描述: 返回格式化的日期字符串，格式为2016-11-12 00:00:00
     * 参数名称:
     * 参数名称
     * 返回内容:
     * 异常说明:
     * 创建用户:
     * 创建时间:
     * 修改用户:
     * 修改时间:
     * 修改内容:
     */
    @Override
    public List<Map<String,Object>> carMaintainList(String sqlStr,List<Object> paramLists)throws Exception {
        List<Map<String,Object>> lists=this.getJdbcDao().queryForMapListBySqlWithParams(sqlStr,paramLists.toArray());
        if(lists.size()>0) {
            return lists;
        }
        return null;
    }



    /**
     * 定保任务 查询定保相关信息
     * @param companyId
     * @param start
     * @param limit
     * @return
     * @throws Exception
     */
    @Override
    public List<Map<String, Object>> carDbMaintainList(String companyId,long beforeSixTime, int start, int limit,String pcode,String code) throws Exception {
        StringBuffer sqlStr=new StringBuffer();

        sqlStr.append(" SELECT " +
                " MAX(t.maintain_time) maintain_time,MAX(t.next_maintain_time) next_maintain_time,MAX(t.next_maintain_mile) next_maintain_mile," +
                " t.plate_num,t.car_id,t.vin,t.contact_name,t.contact_phone,t.company_id " +
                " FROM  t_crm_car_maintain t  WHERE  t.maintian_type != '首保' " +
                " AND t.company_id = ? and t.maintain_time>=? ");

        Constant.REMIND_CLOSE_SQL(sqlStr,pcode,code,"t");
        sqlStr.append(" GROUP by t.vin limit ?,?");
//        sqlStr.append("SELECT * FROM ( " +
//                    "SELECT * FROM ( " +
//                        "SELECT * FROM t_crm_car_maintain " +
//                "           where maintian_type!='首保' and company_id=? and maintain_time>=?  " +
//                "           ORDER BY maintain_time DESC " +
//                        ") temp1 " +
//                "WHERE 1=1 " +
////                "and temp1.vin='LSGBC6356GG103391' " +
//                "");
//        Constant.REMIND_CLOSE_SQL(sqlStr,pcode,code,"temp1");
//        sqlStr.append("NOT EXISTS (SELECT * FROM t_crm_car_remindclose WHERE temp1.car_id = user_carid AND temp1.company_id = company_id  AND temp1.vin = vin )" );

//        sqlStr.append("GROUP BY temp1.car_id ) temp2 limit ?,? ");
        List<Map<String,Object>> lists=this.getJdbcDao().queryForMapListBySqlWithParams(sqlStr.toString(),companyId,beforeSixTime,start,limit);
        if(lists.size()>0){
            return lists;
        }
        return null;
    }

    /**
     * 根据参数 获得公司信息
     * @param mby
     * @param mbr
     * @return
     * @throws Exception
     */
    @Override
    public List<Map<String,Object>> findCompanyList(String mby,String mbr) throws Exception {
        StringBuffer sqlStr=new StringBuffer();
        sqlStr.append("select company_id,p_code from t_bc_param_set where p_code=? or p_code=? group by company_id");
        return this.getJdbcDao().queryForMapListBySqlWithParams(sqlStr.toString(),mby,mbr);
    }

    /**
     * 根据公司ID 参数 获得参数信息
     * @param companyId
     * @param code
     * @return
     * @throws Exception
     */
//    @Override
//    public Map<String,Object> findCompanyParamList(String companyId,String code) throws Exception {
//        Map<String,Object> paramMap=null;
//        StringBuffer sqlStr=new StringBuffer();
//        sqlStr.append("select code,company_id,p_code,`name`,`value` from t_bc_param_set where p_code=? and company_id=?");
//        List<Map<String,Object>> lists=this.getJdbcDao().queryForMapListBySqlWithParams(sqlStr.toString(),code,companyId);
//        if(lists!=null || lists.size()>0){
//            paramMap=new HashMap<>();
//            for(Map<String,Object> map:lists){
//                String key=String.valueOf(map.get("code"));
//                String value=String.valueOf(map.get("value"));
//                paramMap.put(key,value);
//            }
//        }
//        return paramMap;
//    }

    @Override
    public List<Map<String,Object>> findCompanyParamList(String companyId,String code) throws Exception {
        Map<String,Object> paramMap=null;
        StringBuffer sqlStr=new StringBuffer();
        sqlStr.append("select code,company_id,p_code,`name`,`value` from t_bc_param_set where p_code=? and company_id=?");
        List<Map<String,Object>> lists=this.getJdbcDao().queryForMapListBySqlWithParams(sqlStr.toString(),code,companyId);
        if(lists!=null || lists.size()>0){
            return lists;
        }
        return null;
    }


    /**
     * 根据公司、车牌号 获得首保的最后一次进厂时间
     * @param companyId
     * @param plateNum
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, Object> findCarBlanceDate(String companyId, String plateNum,String carId) throws Exception {
        StringBuffer sqlStr=new StringBuffer();
        sqlStr.append("select * from t_crm_car_workorder where wx_type='首保' " +
                "and company_id=? and plate_num=? and car_id=? order by balance_date DESC limit 0,1;");
        Map<String,Object> map=this.getJdbcDao().queryForMapBySqlWithParams(sqlStr.toString(),companyId,plateNum,carId);
        if(map.size()>0){
            return map;
        }
        return null;
    }

    /**
     * 查询工单信息
     * @param sql
     * @param companyId
     * @return
     * @throws Exception
     */
    @Override
    public List<Map<String, Object>> findCarWorkOrderList(String sql, String companyId,int start,int limit) throws Exception {
        List<Map<String,Object>> list=this.getJdbcDao().queryForMapListBySqlWithParams(sql,companyId,start,limit);
        if(list.size()>0){
            return list;
        }
        return null;
    }

    /**
     * ]查询工单详细信息
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    public TCrmCarWorkOrder findWorkOrderInfo(String id) throws Exception {
        return (TCrmCarWorkOrder) this.getHibernateDao().findEntity(TCrmCarWorkOrder.class,id);
    }

    /**
     * 批量更新操作
     * @param list
     */
    @Override
    public void batchUpdateList(List<WorkOrderDTO> list){
        String sql = "update t_crm_car_workorder set wx_type=?,real_amount=? where id=?";
        jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
            public int getBatchSize() {
                return list.size();
                //这个方法设定更新记录数，通常List里面存放的都是我们要更新的，所以返回list.size();
            }
            public void setValues(PreparedStatement ps, int i)throws SQLException {
                WorkOrderDTO orderDTO = (WorkOrderDTO) list.get(i);
                ps.setString(1, orderDTO.getWxType());
                ps.setString(2, orderDTO.getRealAmount());
                ps.setString(3, orderDTO.getId());

            }
        });
    }

    /**
     * 批量处理sql
     * @param list
     */
    @Override
    public void batchUpdateStrList(final List<String> list){
        String[] sqls=list.toArray(new String[list.size()]);
        jdbcTemplate.batchUpdate(sqls);
    }


    /**
     * 批量处理任务信息
     * @param lists
     */
    @Override
    public void insertMaintailLists(final List<TCrmTask> lists){
        String sql="INSERT INTO `t_crm_task` (`id`,  `vin`, `car_id`, " +
                "`company_id`, `contact_id`, `content`, `expect_date`, `is_back`, `link_man`, `link_phone`, `plateNum`, " +
                "`sa_id`, `status`, `type_code`, `type_pcode`,create_time) VALUES (replace(UUID(),'-',''), ?, ?, ?,?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?)";
        jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {

            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                TCrmTask crmTask=lists.get(i);
                ps.setString(1,crmTask.getVIN());
                ps.setString(2,crmTask.getCarId());
                ps.setString(3,crmTask.getCompanyId());
                ps.setString(4,crmTask.getContactId());
                ps.setString(5,crmTask.getContent());
                ps.setString(6,crmTask.getExpectDate());
                ps.setString(7,crmTask.getIsBack());
                ps.setString(8,crmTask.getLinkman());
                ps.setString(9,crmTask.getLinkphone());
                ps.setString(10,crmTask.getPlateNum());
                ps.setString(11,crmTask.getSaId());
                ps.setString(12, crmTask.getStatus());
                ps.setString(13,crmTask.getTypeCode());
                ps.setString(14,crmTask.getTypePCode());
                ps.setLong(15,new Date().getTime());
            }

            @Override
            public int getBatchSize() {
                return lists.size();
            }
        });
    }

    @Override
    public List<TCrmCarMaintain> findMaintainByCarId(String carId,String vin) throws Exception {
        Map<String,Object> map=new HashMap<>();
        map.put("carId",carId);
        map.put("vin",vin);
        return this.getHibernateDao().findEntityListByHqlWithParams("from TCrmCarMaintain where carId=:carId and vin=:vin ORDER BY maintainTime ASC",map);
    }

    public  void removeCrmTask(String companyId,String startTime,String endTime,String code,String pCode) throws Exception {
        if(!"".equals(startTime) && !"".equals(endTime)){
            //删除指定时间段内的任务信息
            String sql="delete from t_crm_task where company_id=? and type_code=? and type_pcode=? AND temp2.expect_date >=? " +
                    "AND temp2.expect_date <=? ";
            this.executeSQL(sql,companyId,code,pCode,startTime,endTime);
        }

    }
    public  boolean checkCrmTask(String startTime,String endTime,TCrmTask crmTask) throws Exception {
        if("".equals(startTime) && "".equals(endTime)){
            //验证任务是否已经存在
            return crmTaskDao.checkSbTask(crmTask.getCompanyId(),crmTask.getCarId(),crmTask.getTypeCode(),crmTask.getTypePCode(),crmTask.getExpectDate());
        }
        return false;
    }

}
